package com.mobile.collect.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.mobile.collect.R;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.db.EntityManager;

import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;

public class ImageLayoutyouhua extends FrameLayout implements View.OnClickListener {

    List<DevicePointInfo> points;

    FrameLayout layouPoints;

    private ZoomImageView imgBg;
    private float iX, iY, iScale = 1;


    Context mContext;
    ImageLayoutListener listener;
    OnLayoutSuccessListener onLayoutSuccessListener;

    public ImageLayoutyouhua(Context context) {
        this(context, null);
    }

    public ImageLayoutyouhua(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ImageLayoutyouhua(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }


    private void initView(Context context, AttributeSet attrs) {

        mContext = context;
        points = new ArrayList<>();
        View imgPointLayout = inflate(context, R.layout.layout_imgview_point, this);

        imgBg = imgPointLayout.findViewById(R.id.imgBg);
        layouPoints = (FrameLayout) imgPointLayout.findViewById(R.id.layouPoints);

        imgBg.setOnScanListener(new ZoomImageView.OnScanListener() {
            @Override
            public void onChanged(float x, float y, float scale) {
                refreshPoints(x, y, scale);
            }
        });

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    public void setImgBg(int width, int height, String picPath) {
        this.width = width;
        this.height = height;
        Glide.with(mContext).load(picPath).asBitmap().listener(new RequestListener<String, Bitmap>() {
            @Override
            public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
                listener.toSetBitMapInfo(resource.getWidth(), resource.getHeight());
                return false;
            }
        }).into(imgBg);
    }

    public void setPoints(List<DevicePointInfo> points) {
        this.points = points;
    }


    private void refreshPoints(float x, float y, float scale) {
        iScale = scale;
        iX = x;
        iY = y;
        NLog.e("refreshPoints", "x=" + x + " y=" + y + " scale=" + scale);
        if (null != points && points.size() > 0) {
            for (DevicePointInfo point : points) {
                setNewXY(point);
                View view = point.getPointView();
//                double scaleX = point.getScaleX();
//                double scaleY = point.getScaleY();
//

//
//                double newX = x + width * scale * scaleX;
//                double newY = y + height * scale * scaleY;
//
//                double pointX = width * scaleX* scale;//点的最原始坐标缩放后的大小
//                double pointY = height * scaleY* scale;//点的最原始坐标缩放后的大小
//
//                String dircetion = point.getPointDircetion();
//                if (TextUtils.isEmpty(dircetion)) {
//                    dircetion = "up";
//                }
//                int txtWidth;
//                int txtHeight;
//                int lineWidth;
//
//                if (point.getLineType() == 0) {
//                    txtWidth = 60;
//                    txtHeight = 26;
//                    lineWidth = 25;
//                }else{
//                    txtWidth = 60;
//                    txtHeight = 26;
//                    lineWidth = 75;
//                }
//
//
//                switch (dircetion) {
//                    case "up":
//                        newX = pointX  + (scale - 1) * (Kits.Dimens.dp2px(txtWidth))/2+x;
//                        newY = pointY +(scale - 1)*Kits.Dimens.dp2px(txtHeight+lineWidth)+y;
//                        break;
//                    case "down":
//                        newX = pointX + (scale - 1) * (Kits.Dimens.dp2px(txtWidth))/2+x;
//                        newY = pointY+y;
//                        break;
//                    case "left":
//                        newX = pointX+(scale - 1) * (Kits.Dimens.dp2px(txtWidth+lineWidth))+x;
//                        newY = pointY+(scale-1)*Kits.Dimens.dp2px(txtHeight)/2+y;
//                        break;
//                    case "right":
//                        newX = pointX +x;
//                        newY = pointY+(scale-1)*Kits.Dimens.dp2px(txtHeight)/2+y;
//                        break;
//                    default:
//
//                }
//
//                view.setX((float) newX);
//                view.setY((float) newY);

                point.setViewWidth(view.getWidth());
                point.setViewHeight(view.getHeight());

            }
        }

    }


    private void setNewXY(DevicePointInfo point){
        int txtWidth;
        int txtHeight;
        int lineWidth;

        if (point.getLineType() == 0) {
            txtWidth = 60;
            txtHeight = 26;
            lineWidth = 25;
        }else{
            txtWidth = 60;
            txtHeight = 26;
            lineWidth = 75;
        }
        double scaleX = point.getScaleX();
        double scaleY = point.getScaleY();

        View view = point.getPointView();
        double pointX = width * scaleX* iScale;//点的最原始坐标缩放后的大小
        double pointY = height * scaleY* iScale;//点的最原始坐标缩放后的大小

        String dircetion = point.getPointDircetion();
        if (TextUtils.isEmpty(dircetion)) {
            dircetion = "up";
        }
        double newX =0;
        double newY = 0;
        switch (dircetion) {
            case "up":
                newX = pointX  + (iScale - 1) * (Kits.Dimens.dp2px(txtWidth))/2+iX;
                newY = pointY +(iScale - 1)*Kits.Dimens.dp2px(txtHeight+lineWidth)+iY;
                break;
            case "down":
                newX = pointX + (iScale - 1) * (Kits.Dimens.dp2px(txtWidth))/2+iX;
                newY = pointY+iY;
                break;
            case "left":
                newX = pointX+(iScale - 1) * (Kits.Dimens.dp2px(txtWidth+lineWidth))+iX;
                newY = pointY+(iScale-1)*Kits.Dimens.dp2px(txtHeight)/2+iY;
                break;
            case "right":
                newX = pointX +iX;
                newY = pointY+(iScale-1)*Kits.Dimens.dp2px(txtHeight)/2+iY;
                break;
            default:
        }
        view.setX((float) newX);
        view.setY((float) newY);
    }

    float width;
    float height;

    public void addPoints(List<DevicePointInfo> list) {
        Log.d("onLayout", "addPoints");
        points.clear();
        layouPoints.removeAllViews();
        this.points.addAll(list);

        for (int i = 0; i < points.size(); i++) {
            final DevicePointInfo pointInfo = points.get(i);
            addPoint(pointInfo);
        }
    }


    public void addPoint(final DevicePointInfo pointInfo) {
        double width_scale = pointInfo.getScaleX();
        double height_scale = pointInfo.getScaleY();
        Log.d("addPoint", "width_scale" + width_scale);
        Log.d("addPoint", "height_scale" + height_scale);
        MyPointView view;
        if (pointInfo.getLineType() == 0) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point, this, false);
        } else {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point3, this, false);
        }

        pointInfo.setPointView(view);

        view.setPointInfo(pointInfo,false);

        layouPoints.addView(view);

        setNewXY(pointInfo);
        setTagTouchEvents(pointInfo);
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(pointInfo);
            }
        });
    }


    private void setLineType(DevicePointInfo pointInfo) {
        layouPoints.removeView(pointInfo.getPointView());
        addPoint(pointInfo);
    }

    private void showDialog(DevicePointInfo pointInfo) {
//        PointDialog pointDialog = new PointDialog(getContext(), new PointDialog.PointDialogListener() {
//            @Override
//            public void toSetLine(DevicePointInfo pointInfo,int newLineType) {
//                setLineType(pointInfo);
//            }
//
//            @Override
//            public void toUpdate(DevicePointInfo info) {
//                listener.toUpdatePoint(info);
//            }
//
//            @Override
//            public void toDel(DevicePointInfo info) {
//                layouPoints.removeView(info.getPointView());
//                listener.toDelPoint(info);
//            }
//
//            @Override
//            public void toChangeDirection(DevicePointInfo pointInfo, int direction) {
//
//            }
//        });
//        pointDialog.display(pointInfo);
    }


    @Override
    public void onClick(View view) {
        int pos = (int) view.getTag();
        Toast.makeText(getContext(), "pos : " + pos, Toast.LENGTH_SHORT).show();
    }

    private void setTagTouchEvents(final DevicePointInfo pointInfo) {
        final View tagView = pointInfo.getPointView();
        final GestureDetector mGestureDetector = new GestureDetector(getContext(), new GestureDetector.OnGestureListener() {
            int lastX;
            int lastY;
            boolean isMoveing;

            @Override
            public boolean onDown(MotionEvent event) {
                lastX = (int) event.getX();
                lastY = (int) event.getY();
                isMoveing = false;
                return true;
            }

            @Override
            public void onShowPress(MotionEvent e) {
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (!isMoveing && canEdit) {
                    showDialog(pointInfo);
                }
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent event, float distanceX, float distanceY) {
                NLog.e("setTagTouchEvents", "distanceX=" + distanceX);
                NLog.e("setTagTouchEvents", "distanceY=" + distanceY);

                if (!canEdit) {
                    return false;
                }

                isMoveing = true;
                int x = (int) event.getX();
                int y = (int) event.getY();

                int offsetX = x - lastX;
                int offsetY = y - lastY;
                tagView.setX(tagView.getX() + offsetX);
                tagView.setY(tagView.getY() + offsetY);
                count(pointInfo);
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                return false;
            }

        });

        tagView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mGestureDetector.onTouchEvent(event);
            }
        });


    }

    private void count(final DevicePointInfo pointInfo) {
        final View tagView = pointInfo.getPointView();
        float x = tagView.getX();
        float y = tagView.getY();

        float scaleX = (x - iX) / (width * iScale);
        float scaley = (y - iY) / (height * iScale);

        int txtWidth = 60;
        int txtHeight = 26;
        int lineWidth = 25;

        if (pointInfo.getLineType() == 0) {
             txtWidth = 60;
             txtHeight = 26;
             lineWidth = 25;
        }else{
            txtWidth = 60;
            txtHeight = 26;
            lineWidth = 75;
        }

        switch (pointInfo.getPointDircetion()) {
            case "up":
                scaleX = (x-(iScale - 1) * (Kits.Dimens.dp2px(txtWidth))/2-iX)/(width *iScale);
                scaley = (y - (iScale - 1)*Kits.Dimens.dp2px(txtHeight+lineWidth) -iY)/(height*iScale);
                break;
            case "down":
                scaleX = (x - ( (iScale - 1) * (Kits.Dimens.dp2px(txtWidth))/2+iX))/(width *iScale);
                scaley = (y-iY)/(height*iScale);
                break;
            case "left":
                scaleX = (x -((iScale - 1) * (Kits.Dimens.dp2px(txtWidth+lineWidth))+iX))/(width *iScale);
                scaley = (y-((iScale-1)*Kits.Dimens.dp2px(txtHeight)/2+iY))/(height*iScale);
                break;
            case "right":
                scaleX = (x-iX)/(width *iScale);
                scaley = (y-((iScale-1)*Kits.Dimens.dp2px(txtHeight)/2+iY))/(height*iScale);
                break;
            default:

        }
        pointInfo.setScaleX(scaleX);
        pointInfo.setScaleY(scaley);
        pointInfo.setScreenX((int) (width * scaleX));
        pointInfo.setScreenY((int) (height * scaley));

        EntityManager.getInstance().savePointInfo(pointInfo);
    }

    public interface ImageLayoutListener {
        void toUpdatePoint(DevicePointInfo pointInfo);

        void toDelPoint(DevicePointInfo pointInfo);

        void toSetBitMapInfo(int width, int height);
    }

    public ImageLayoutListener getListener() {
        return listener;
    }

    public void setListener(ImageLayoutListener listener) {
        this.listener = listener;
    }

    boolean canEdit;

    public void setCanEdit(boolean canEdit) {
        this.canEdit = canEdit;
    }

    boolean loadSuccess;

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int layoutPointsWidth = layouPoints.getWidth();
        if (layoutPointsWidth != 0 && !loadSuccess) {
            loadSuccess = true;
            onLayoutSuccessListener.onLayoutSuccess();
        }
    }

    public void setOnLayoutSuccessListener(OnLayoutSuccessListener onLayoutSuccessListener) {
        this.onLayoutSuccessListener = onLayoutSuccessListener;
    }

    public interface OnLayoutSuccessListener {
        void onLayoutSuccess();
    }
}
